<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">用户管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>用户管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar">
            搜索：
            <select id="sysUser-search-key">
                <option value="">-请选择-</option>
                <option value="user_id">ID</option>
                <option value="username">账号</option>
                <option value="nickname">用户名</option>
                <option value="phone">手机号</option>
                <option value="email">邮箱</option>
            </select>&emsp;
            <input id="sysUser-search-value" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
            <button id="sysUser-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
            <button id="sysUser-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
<!--            <button id="sysUser-btn-export" class="layui-btn icon-btn"><i class="layui-icon">&#xe601;</i>导出</button>-->
        </div>

        <table class="layui-table" id="sysUser-table" lay-filter="sysUser-table"></table>
    </div>
</div>


<!-- 表格操作列 -->
<script type="text/html" id="sysUser-table-bar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reset">重置密码</a>
    <a class="layui-btn layui-btn-xs" lay-event="roles">分配角色</a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="sysUser-tpl-state">
    <input type="checkbox" lay-filter="sysUser-tpl-state" value="{{d.user_id}}" lay-skin="switch" lay-text="正常|锁定"
           {{d.status==0?'checked':''}}/>
</script>

<script>
    layui.use(['form', 'table', 'util', 'config', 'admin'], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        var admin = layui.admin;

        //if( admin.hasPerm('sysUser:add') ) {
        //   $('#btnAdd').hide();
        //}

        // 添加按钮绑定权限
        if(!admin.hasPerm('sysUser:post/users/saveOrUpdate')) {
            $('#sysUser-btn-add').hide();
        }
    	
        // 导出按钮绑定权限
        if(!admin.hasPerm('sysUser:post/users/saveOrUpdate')) {
            $('#sysUser-btn-export').hide();
        }
        
        
        
        // 渲染表格
        let mytable = table.render({
            elem: '#sysUser-table',
            // url: config.base_server + 'user_query.json',
            url: config.base_server + 'api-sys/api/sysUser/list',
            method: 'GET',
            // request: {
            //     limitName: 'pageSize' //每页数据量的参数名，默认：limit
            // },
            where: {
                access_token: config.getToken().access_token
            },
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'user_id', sort: true, title: '用户编号'},
                {field: 'username', sort: true, title: '账号'},
                {field: 'nickname', sort: true, title: '用户名'},
                {field: 'phone', title: '手机号'},
                {sort: true, title: '性别',templet:function (d) {
                        return d.sex==0?"男":"女"
                    }},
                {field: 'createDate',sort: true,  title: '创建时间'},
                {field: 'status', sort: true, templet: '#sysUser-tpl-state', title: '状态'},
                {align: 'center', toolbar: '#sysUser-table-bar', title: '操作',width: 300}
            ]]
        });

        // 添加按钮点击事件
        $('#sysUser-btn-add').click(function () {
            showEditModel();
        });

        // 工具条点击事件
        table.on('tool(sysUser-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            }else if (layEvent === 'del') { //删除
                doDelete(obj);
            } else if (layEvent === 'reset') { // 重置密码
                layer.confirm('确定重置此用户的密码吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    console.log(obj.data.username);
                    admin.req('api-sys/api/sysUser/resetMima?access_token='+config.getToken().access_token+'&username='+obj.data.username, {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'PATCH');
                });
            }else if (layEvent === 'roles'){//分配角色
                showRolesModel(data);
            }
        });
        // 删除
        var doDelete = function (obj) {
            layer.confirm('确定要删除吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('api-sys/api/sysUser/del/' + obj.data.user_id, {}, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        obj.del();
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'DELETE');
            });
        };
        //显示表单弹窗
        var showEditModel = function (data) {
            //修改sex值
            if (data){
                data.sex = data.sex+'';
            }
            admin.putTempData('t_user', data);
            var title = data ? '修改用户' : '添加用户';
            admin.popupCenter({
                title: title,
                path: 'pages/system/user_form.html',
                finish: function () {
                    table.reload('sysUser-table', {});
                }
            });
        };
        //显示角色弹窗
        var showRolesModel = function (data){
            admin.putTempData('t_user', data);
            var title = '分配角色';
            admin.popupCenter({
                title:title,
                path:'pages/system/user_role.html',
                finish:function (){
                    table.reload('sysUser-table', {});
                }
            })
        }
        // var showRolesModel = function (obj) {
        //     var title = '分配角色';
        //     $.ajax({
        //         url:'pages/system/user_role.html?user_id='+obj.data.user_id,
        //         type:'GET',
        //         dataType:'html',
        //         success:function (data){
        //             layer.open({
        //                 type: 1,
        //                 title: title,
        //                 btn: ['保存', '关闭'],
        //                 area: ['200px', '200px'],
        //                 content: template.render(data,{user_id:obj.data.user_id}),
        //                 async:false,
        //                 yes: function (index) {
        //
        //                     // var params = []
        //                     // var nodes = xtree3.GetAllCheckBox();
        //                     // var _index = 0;
        //                     // for (var i = 0; i < nodes.length; i++) {
        //                     //     if (nodes[i].checked && nodes[i].value !== 'on') {
        //                     //         var param = {};
        //                     //         param.permissionId = nodes[i].value;
        //                     //         param.roleId = obj.data.role_id;
        //                     //         params[_index] = param;
        //                     //         _index++;
        //                     //     }
        //                     // }
        //                     admin.req('api-sys/role/updateRoles?access_token=' + config.getToken().access_token,
        //                         JSON.stringify(params), function (data) {
        //                             layer.closeAll('loading');
        //                             if (0 === data.code) {
        //                                 layer.msg(data.msg, {icon: 1, time: 500});
        //                                 layer.close(index);
        //                             } else {
        //                                 layer.msg(data.msg, {icon: 2, time: 500});
        //                             }
        //                         }, 'PATCH');
        //                 }
        //             })
        //         }
        //     })
        // }
        // 搜索按钮点击事件
        $('#sysUser-btn-search').click(function () {
            var key = $('#sysUser-search-key').val();
            var value = $('#sysUser-search-value').val();
            var data = {};
            data[key] = value;
            // table.reload('sysUser-table', {where: data});
            myTable.reload({where: data});
        });

        // 导出
        $('#sysUser-btn-export').click(function () {
            var url = config.base_server + 'api-sys/api/sysUser/exportUser?access_token='+config.getToken().access_token;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = "blob";
            xhr.setRequestHeader("client_type", "DESKTOP_WEB");
            xhr.onload = function() {
                if (this.status == 200) {
                    var blob = this.response;
                    var objecturl = URL.createObjectURL(blob);
                    window.location.href = objecturl;
                }
            }
            xhr.send();
        });
        form.on('switch(sysUser-tpl-state)', function (obj) {
            layer.load(2);
            admin.req('api-sys/api/sysUser/updateStatus?access_token='+config.getToken().access_token, JSON.stringify({
                user_id: this.value,
                status: obj.elem.checked ? 0 : 1
            }), function (data) {
                layer.closeAll('loading');
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    //table.reload('table-sysUser', {});
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'PATCH');
        });
    });
</script>